package org.csu.mall.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.csu.mall.entity.User;
import org.csu.mall.persistence.UserMapper;
import org.csu.mall.service.ICategoryService;
import org.csu.mall.service.IFileService;
import org.csu.mall.service.IShopService;
import org.csu.mall.utils.PropertiesUtil;
import org.csu.mall.common.CONSTANT;
import org.csu.mall.common.ResponseCode;
import org.csu.mall.common.UniformResponse;
import org.csu.mall.entity.Category;
import org.csu.mall.entity.Product;
import org.csu.mall.persistence.CategoryMapper;
import org.csu.mall.persistence.ProductMapper;
import org.csu.mall.service.IProductService;
import org.csu.mall.utils.UsernameUtil;
import org.csu.mall.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IShopService shopService;

//    @Autowired
//    private IFileService iFileService;



    @Override
    public UniformResponse<ProductVO> getProductDetail(Integer productId){
        if(productId == null){
            return UniformResponse.createForErrorCodeMessage(
                    ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDescription());
        }
        Product product = productMapper.selectById(productId);
        if(product == null){
            return UniformResponse.createForErrorMessage("产品不存在或已删除");
        }
        if(product.getStatus() != CONSTANT.ProductStatus.ON_SALE.getCode()){
            return UniformResponse.createForErrorMessage("产品不在售，下架或其他情况");
        }
        ProductVO productVO = entityToVO(product);
        return UniformResponse.createForSuccess(productVO);
    }

    //todo 非模糊搜索
    @Override
    public UniformResponse<List<Product>> searchByText(String info) {
        Category category=categoryMapper.selectOne(Wrappers.<Category>query().eq("name",info));
        if(category==null)
        {
            List<Product> product=productMapper.selectList(Wrappers.<Product>query().eq("name",info));
            if(product==null)
            {
                return UniformResponse.createForErrorMessage("抱歉，没有找到与\""+info+"\"相关的商品") ;
            }
            return UniformResponse.createForSuccess(product);
        }
        List<Product> productList=productMapper.selectList(Wrappers.<Product>query().eq("category_id",category.getId()));//使用数据库的列名
        if(productList==null)
        {
            return UniformResponse.createForErrorMessage("抱歉，目前在\""+info+"\"类别下暂无商品上架");
        }
        return UniformResponse.createForSuccess(productList);
    }

    @Override
    public UniformResponse<List<Product>> searchByLabel(String label) {
        Category category=categoryMapper.selectOne(Wrappers.<Category>query().eq("name",label));
        List<Product> productList=productMapper.selectList(Wrappers.<Product>query().eq("category_id",category.getId()));
        if(productList==null)
        {
            return UniformResponse.createForErrorMessage("抱歉，目前在\""+label+"\"类别下暂无商品上架");
        }
        return UniformResponse.createForSuccess(productList);
    }

    private ProductVO entityToVO(Product product){
        ProductVO productVO = new ProductVO();

        productVO.setId(product.getId());
        productVO.setSubtitle(product.getSubtitle());
        productVO.setPrice(product.getPrice());
        productVO.setMainImage(product.getMainImage());
        productVO.setSubImages(product.getSubImages());
        productVO.setCategoryId(product.getCategoryId());
        productVO.setDetail(product.getDetail());
        productVO.setName(product.getName());
        productVO.setStatus(product.getStatus());
        productVO.setStock(product.getStock());

        //todo 要去验证输出日期字符串的格式是否和前端要求一致
        productVO.setCreateTime(product.getCreateTime().toString());
        productVO.setUpdateTime(product.getUpdateTime().toString());

        Category category = categoryMapper.selectById(product.getCategoryId());
        productVO.setParentCategoryId(category.getParentId());
        //imageHost
        productVO.setImageHost(PropertiesUtil.getProperty("image.server.url"));
        return productVO;
    }
    public UniformResponse productList(Integer categoryId,String keyword,int pageNum,int pageSize,String orderBy){
        //todo ProductListVO

            Page<Product> result = new Page<>();
            result.setCurrent(pageNum);
            result.setSize(pageSize);
            QueryWrapper<Product> query = new QueryWrapper<>();
            //查询条件中增加分类查询
            if(categoryId!=null) {
                List<Integer> categoryIdList = categoryService.getAllChildrenCategory(categoryId).getData();
                query.in("category_id", categoryIdList);
            }

            //查询条件中增加按分类名称模糊查询
            if (StringUtils.isNotBlank(keyword)) {
                keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
                query.like("name", keyword);
            }


            //排序
            if (StringUtils.isNotBlank(orderBy)) {
                if (CONSTANT.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
                    String[] orderByStrings = orderBy.split("_");
                    if (StringUtils.equals(orderByStrings[1], "asc")) {
                        query.orderByAsc(orderByStrings[0]);
                    } else if (StringUtils.equals(orderByStrings[1], "desc")) {
                        query.orderByDesc(orderByStrings[0]);
                    }

                }
            }
            result = productMapper.selectPage(result, query);


            return UniformResponse.createForSuccess(result);

    }

    @Override
    public UniformResponse recommendProduct(String keyword,Integer pageNum,Integer pageSize) {
        Page<Product> result = new Page<>();
        result.setCurrent(pageNum);
        result.setSize(pageSize);
        QueryWrapper<Product> query = new QueryWrapper<>();
        keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        query.like("name", keyword).orderByAsc("price");
        result = productMapper.selectPage(result, query);
        return UniformResponse.createForSuccess(result);
    }

    @Override
    public UniformResponse getProducts(int pageNum, int pageSize) {
        String username= UsernameUtil.getUsername("username");
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));
        if(username==null){
            return UniformResponse.notLogining();
        }else {
            Page<Product> result = new Page<>();
            result.setCurrent(pageNum);
            result.setSize(pageSize);
            User user=userMapper.selectById(userId);
            QueryWrapper<Product> query = new QueryWrapper<>();
            //
//            if(user.getShopId().equals(CONSTANT.SHOPID))
//            {
//                return UniformResponse.createForErrorMessage("该用户未开店");
//            }
            query.eq("shop_id", user.getShopId()).orderByAsc("category_id").orderByDesc("update_time");
            result = productMapper.selectPage(result, query);
            return UniformResponse.createForSuccess(result);
        }

    }

    @Override
    public UniformResponse<Product> addProduct(Integer categoryId, String subTitle, String mainImage, String subImages, String detail, BigDecimal price, Integer stock, Integer status, String name) throws IOException {
        String username= UsernameUtil.getUsername("username");
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));
        if(username==null){
            return UniformResponse.notLogining();
        }else {
            User user=userMapper.selectById(userId);
            QueryWrapper<Product> query = new QueryWrapper<>();
            query.eq("name", name).eq("shop_id",user.getShopId());
            Product have = productMapper.selectOne(query);
            Product product = new Product();
            if (have == null) {
                product.setName(name);
                product.setStatus(status);
                product.setStock(stock);
                QueryWrapper<Category> queryCategory = new QueryWrapper<>();
                queryCategory.eq("id", categoryId);
                Category categoryExit = categoryMapper.selectOne(queryCategory);
                if (categoryExit == null) {
                    return UniformResponse.createForErrorMessage("添加商品失败,无该类别");
                }
                product.setCategoryId(categoryId);
                Map<String,String> map=uploadPhoto(mainImage,subImages,name);
                product.setMainImage("../img/"+map.get("main_image"));
                product.setSubImages("../img/"+map.get("sub_image"));
                product.setSubtitle(subTitle);
                product.setDetail(detail);
                product.setName(name);
                product.setPrice(price);
//                if(shopService.checkShopIsOpen().getStatus()==1)
//                {
//                    User user=userMapper.selectById(userId);
//                    product.setShopId(user.getShopId());
//                }
//                product.setShopId(CONSTANT.SHOPID);
                product.setShopId(user.getShopId());
                product.setCreateTime(LocalDateTime.now());
                product.setUpdateTime(LocalDateTime.now());
                productMapper.insert(product);
                return UniformResponse.createForSuccess("添加商品成功",product);

            }


            return UniformResponse.createForErrorMessage("添加商品失败，已有该商品");
        }
    }

    @Override
    public UniformResponse<String> deleteProduct(Integer productId) {
        String username= UsernameUtil.getUsername("username");
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));
        if(username==null){
            return UniformResponse.notLogining();
        }else {
            QueryWrapper<Product> query = new QueryWrapper<>();
            query.eq("id", productId);
            Product product = productMapper.selectOne(query);
            if (product != null) {

//            product.setStatus(CONSTANT.ProductStatus.OFF_SALE.getCode());
//            product.setUpdateTime(LocalDateTime.now());
//            productMapper.updateById(product);
                productMapper.deleteById(productId);
                return UniformResponse.createForSuccess("删除商品成功");
            }
            return UniformResponse.createForErrorMessage("删除商品失败");
        }

    }

    @Override
    public UniformResponse<Product> updateProduct(Integer productId, Integer categoryId, String subTitle, String mainImage, String subImages, String detail, BigDecimal price, Integer stock, Integer status, String name) {
        String username = UsernameUtil.getUsername("username");
        Integer userId=Integer.parseInt(UsernameUtil.getUserId("userid"));
        if (username == null) {
            return UniformResponse.notLogining();
        } else {
            QueryWrapper<Product> query = new QueryWrapper<>();
            query.eq("id", productId);
            Product product = productMapper.selectOne(query);
            if (product != null) {
                product.setCategoryId(categoryId);
                product.setSubImages(subImages);
                product.setSubtitle(subTitle);
                product.setStatus(status);
                product.setPrice(price);
                product.setName(name);
                product.setDetail(detail);
                product.setMainImage(mainImage);
                product.setStock(stock);
                User user=userMapper.selectById(userId);
                product.setShopId(user.getShopId());
                product.setUpdateTime(LocalDateTime.now());
                productMapper.updateById(product);
                return UniformResponse.createForSuccess("更新商品成功", product);
            }
            return UniformResponse.createForErrorMessage("更新商品失败");
        }
    }

//    @Override
//    public UniformResponse upload(MultipartFile file) {
//        String path =PropertiesUtil.getProperty("image.server.url");
//        String targetFileName = iFileService.upLoadFile(file,path);
//        String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
//        Map fileMap = Maps.newHashMap();
//        fileMap.put("uri",targetFileName);
//        fileMap.put("url",url);
//        return UniformResponse.createForSuccess("上传文件成功", fileMap);
//
//    }
    private Map<String,String> uploadPhoto(String idPhotoUrl,String idPhotoUrl2,String name) throws IOException {
        Map<String, String> photos = new HashMap<>();
        //对字节数组字符串进行Base64解码并生成图片
        if (idPhotoUrl == null || idPhotoUrl2 == null) { //图像数据为空
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = new byte[0];
        if (idPhotoUrl.contains("data:image/png;base64")) {
            //Base64解码
            b = decoder.decodeBuffer(idPhotoUrl.replace("data:image/png;base64,", ""));
        }
        if (idPhotoUrl.contains("data:image/jpeg;base64")) {
            //Base64解码
            b = decoder.decodeBuffer(idPhotoUrl.replace("data:image/jpeg;base64,", ""));
        }
//idPhotoUrl = idPhotoUrl.replace("data:image/jpeg;base64,", "");
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {//调整异常数据
                b[i] += 256;
            }
        }
//生成jpg图片
//        Properties prop = new Properties();
//        InputStream ins = this.getClass().getResourceAsStream("csumall.properties");
//        prop.load(ins);
        //读取配置文件
        //主图路径
        String photoname=name+"_main.jpg";
        String imgFilePath = PropertiesUtil.getProperty("image.server.url") + photoname;//新生成的图片
        OutputStream out = new FileOutputStream(imgFilePath);
        out.write(b);
        out.flush();
        out.close();
        photos.put("main_image", photoname);


        byte[] b2 = new byte[0];
        if (idPhotoUrl2.contains("data:image/png;base64")) {
            //Base64解码
            b2 = decoder.decodeBuffer(idPhotoUrl2.replace("data:image/png;base64,", ""));
        }
        if (idPhotoUrl2.contains("data:image/jpeg;base64")) {
            //Base64解码
            b2 = decoder.decodeBuffer(idPhotoUrl2.replace("data:image/jpeg;base64,", ""));
        }
//idPhotoUrl = idPhotoUrl.replace("data:image/jpeg;base64,", "");
        for (int i = 0; i < b2.length; ++i) {
            if (b2[i] < 0) {//调整异常数据
                b2[i] += 256;
            }
        }
//生成jpg图片
        //子图路径
        String photoname2=name+"_mini.jpg";
        String imgFilePath2 = PropertiesUtil.getProperty("image.server.url") + photoname2;//新生成的图片
        OutputStream out2 = new FileOutputStream(imgFilePath2);
        out2.write(b2);
        out2.flush();
        out2.close();

        photos.put("sub_image", photoname2);
        return photos;
    }
}
